import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
// import Layout from '@/layout'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

let accessRoutes = []

const pathFind = (path, routes, parentPath) => {
  // console.log(routes)
  // return true
  if (routes) {
    for (let n = 0; n < routes.length; n++) {
      const route = routes[n]
      let routePath = route.path
      if (routePath.substring(0, 1) !== '/' && parentPath) {
        if (parentPath.substring(parentPath.length - 1, parentPath.length) === '/') {
          routePath = parentPath + routePath
        } else {
          routePath = parentPath + '/' + routePath
        }
      }
      // console.log('routePath', routePath, path)
      if (routePath === path) {
        return true
      }
      if (pathFind(path, route.children, routePath)) {
        return true
      }
    }
  }
  return false
}

const PATH_REDIRECT = '/redirect'
const pathExists = (path) => {
  if (path.indexOf(PATH_REDIRECT) === 0) {
    path = path.substring(PATH_REDIRECT.length, path.length)
  }
  if (pathFind(path, router.options.routes)) {
    return true
  }
  if (pathFind(path, accessRoutes)) {
    return true
  }
  return false
}

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // console.log('to', to)
  // determine whether the user has logged in
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      // determine whether the user has obtained his permission roles through getInfo
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        // console.log(router.options.routes)
        // console.log('to', to.fullPath)
        if (pathExists(to.path, accessRoutes)) { // 存在页面
          // console.log('next', to.path)
          next()
        } else { // 不存在页面
          Message({
            message: '找不到页面 ' + to.path,
            type: 'error',
            duration: 5 * 1000
          })
          next('/dashboard')
        }
      } else {
        try {
          // get user info
          // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
          const { roles } = await store.dispatch('user/getInfo')
          // console.log('beforeEach aaa')
          // generate accessible routes map based on roles
          accessRoutes = await store.dispatch('permission/generateRoutes', roles)
          // dynamically add accessible routes
          // console.log('accessRoutes', accessRoutes)
          router.addRoutes(accessRoutes)

          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          next({ ...to, replace: true })
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
